package client;

import communication.BandwidthConnection;
import constans.CapsuleConstans;
import constans.ConfigurationConstans;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class Configuration implements ConfigurationConstans {


    private Properties prop;


    public Configuration() {
        this.prop = new Properties();
    }


    public long getOfferSpace(){
        try{
            return Long.parseLong(prop.getProperty("OfferSpace"));
        } catch (NumberFormatException error) {
            prop.setProperty("OfferSpace",String.valueOf(CapsuleConstans.CAPSULE_LENGTH));
        } catch (NullPointerException error) {
            prop.setProperty("OfferSpace",String.valueOf(CapsuleConstans.CAPSULE_LENGTH));
        }

        return CapsuleConstans.CAPSULE_LENGTH;
    }


    public BandwidthConnection getBandwidth(){
        try{
            return BandwidthConnection.valueOf(prop.getProperty("Bandwidth"));
        } catch (IllegalArgumentException error) {
            prop.setProperty("Bandwidth", ConfigurationConstans.BANDWIDTH_DEFAULT.toString());
        } catch (NullPointerException error) {
            prop.setProperty("Bandwidth", ConfigurationConstans.BANDWIDTH_DEFAULT.toString());
        }

        return ConfigurationConstans.BANDWIDTH_DEFAULT;
    }


    public void setOfferSpace(final long offerSpace){
        prop.setProperty("OfferSpace", String.valueOf(offerSpace));
    }


    public void setBandwidth(final BandwidthConnection bandwidth){
        prop.setProperty("Bandwidth", bandwidth.toString());
    }


    public void load(final String filename)
    throws IOException {
        FileReader file = null;
        try {
            file = new FileReader(filename);
            prop.load(file);
            file.close();
        } catch (IOException error) {
            try {
                if (file != null) {
                    file.close();
                    }
            } catch (IOException e) {}
            throw new IOException(error);
        }
    }


    public void save(final String filename)
    throws IOException{
        FileWriter file = null;
            try {
            file = new FileWriter(filename);
            prop.store(file, null);
            file.close();
        } catch (IOException error) {
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException e) {}
            throw new IOException(error);
        }
    }

}
